package com.thz.houserental.infrastructure.auth;

import com.thz.houserental.infrastructure.web.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class THZLoginFilter extends OncePerRequestFilter {
    private final UserService userService;

    public THZLoginFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token != null) {
            String[] split = token.split(" ");
            Claims claims = null;

            if (split.length == 2) {
                claims = JwtUtil.parse(split[1]);
            } else {
                claims = JwtUtil.parse(split[0]);
            }
            if (claims != null) {
                String userId = claims.getSubject();
                UserDetails user = userService.loadUserByUsername(userId);
                Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request,response);
    }
   
}